<?php

namespace app\controller\admin\cnf;

use app\bll\AdminMenu as BllAdminMenu;
use app\bll\Plugin as BllPlugin;
use core\controller\AdminBase;
use Doctrine\DBAL\Driver\OCI8\ExecutionMode;
use Exception;
use support\View;
use Symfony\Component\Console\Tester\Constraint\CommandIsSuccessful;

class AdminMenu extends AdminBase
{
    public function index()
    {
        if (request()->get('type', '') == 'selmenus') {

            $bllAdminMenu = new BllAdminMenu();
            $menus = $bllAdminMenu->cascader(
                belong: request()->get('belong', 1),
                fields: ['id as iid', 'ident', 'pident', 'target', 'title', 'url', 'type', 'sort', 'belong', 'plugin']
            );
            return $this->success(json_decode($menus, true));
        }

        return $this->view();
    }

    public function add()
    {
        $bllAdminMenu = new BllAdminMenu();
        if (is_post()) {
            try {
                $bllAdminMenu->add(request()->post());
            } catch (Exception $ex) {
                return $this->error($ex->getMessage());
            }
            return $this->success();
        } else {


            $bllPlugin = new BllPlugin();
            $plugins = $bllPlugin->select();

            if (request()->get('type', '') == 'selmenus') {

                $menus = $bllAdminMenu->cascader(
                    belong: request()->get('belong', 1),
                );
                return $this->success(json_decode($menus, true));
            }

            View::assign('plugins', $plugins);
            return $this->view();
        }
    }

    public function edit()
    {
        $bllAdminMenu = new BllAdminMenu();
        if (is_post()) {
            try {
                $bllAdminMenu->edit(request()->get('id'), request()->post());
            } catch (Exception $ex) {
                return $this->error($ex->getMessage());
            }
            return $this->success();
        } else {
            $bllPlugin = new BllPlugin();
            $plugins = $bllPlugin->select();

            if (request()->get('type', '') == 'selmenus') {

                $menus = $bllAdminMenu->cascader(
                    belong: request()->get('belong', 1),
                );
                return $this->success(json_decode($menus, true));
            }


            $menuinfo = $bllAdminMenu->find(request()->get('id'));
            View::assign('plugins', $plugins);
            View::assign('menuinfo', $menuinfo);
            return $this->view();
        }
    }

    public function delete()
    {
        try {
            $bllAdminMenu = new BllAdminMenu();
            $bllAdminMenu->delete(request()->get('id'));
        } catch (Exception $ex) {
            return $this->error($ex->getMessage());
        }
        return $this->success();
    }
}
